#include "merged_texture_pack.h"

#include <QApplication>
#include <QFile>
#include <QPixmap>
#include <quazip/quazip.h>
#include <quazip/quazipfile.h>

MergedTexturePack::MergedTexturePack(QObject* parent)
    : QObject(parent), description_(
        QString("Merged texture pack created by %1 %2").arg(
            qApp->applicationName(),
            qApp->applicationVersion())) {
}

bool MergedTexturePack::save(const QString& out_filename) {
  QFile out_zipfile(out_filename);
  if (out_zipfile.exists()) {
    if (!out_zipfile.remove()) {
      return false;
    }
  }
  QuaZip out_zip(&out_zipfile);
  if (!out_zip.open(QuaZip::mdCreate)) {
    return false;
  }
  out_zip.setComment(QString("Created by %1 %2").arg(
      qApp->applicationName(),
      qApp->applicationVersion()));
  QuaZipFile pack_txt(&out_zip);
  if (!pack_txt.open(QIODevice::WriteOnly, QuaZipNewInfo("pack.txt"))) {
    return false;
  }
  pack_txt.write(description_.toUtf8());
  pack_txt.close();
  if (!pack_image_.isNull()) {
    QuaZipFile pack_png(&out_zip);
    if (!pack_png.open(QIODevice::WriteOnly, QuaZipNewInfo("pack.png"))) {
      return false;
    }
    if (!pack_image_.save(&pack_png, "PNG")) {
      return false;
    }
    pack_png.close();
  }
  foreach (const QString& filename, pixmaps_.keys()) {
    QuaZipFile tilesheet(&out_zip);
    if (!tilesheet.open(QIODevice::WriteOnly, QuaZipNewInfo(filename))) {
      return false;
    }
    if (!pixmaps_.value(filename).save(&tilesheet, "PNG")) {
      return false;
    }
    tilesheet.close();
  }
  out_zip.close();
  if (out_zip.getZipError() != ZIP_OK) {
    return false;
  }
  return true;
}
